package org.example.forum.controller;

import io.micrometer.common.lang.NonNull;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Board;
import org.example.forum.services.IBoardService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@Tag(name = "板块接口")
@RequestMapping("/board")
public class BoardController {
    @Value("${xz-forum.index.board-num:9}")
    private Integer indexBoardNum;



    @Resource
    private IBoardService boardService;


    @Operation(summary = "获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>>  topList(){
        //打印日志
        log.info("首页板块个数为:"+indexBoardNum);
         //调用service查询数据
        List<Board> boards = boardService.selectByNum(indexBoardNum);
        //判断板块是否为空 为空则建一个空list
        if(boards == null){
            boards = new ArrayList<>();
        }
        return AppResult.success(boards);
    }


    @Operation(summary = "获取版块信息")
    @GetMapping("getById")
    public AppResult<Board> getById (@Parameter(description = "版块Id") @RequestParam("id") @NonNull Long id) {
        // 调用Service
        Board board = boardService.selectById(id);
        // 对查询结果进行校验
        if (board == null || board.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 返回结果
        return AppResult.success(board);
    }
}
